#include <sys/types.h>
#include <sys/socket.h>
#include <stdio.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>

#define PORT 9999
#define QUEUE   20
#define BUFFER_SIZE 1024

int main()
{
	int server_sock;
	struct sockaddr_in server_address;
    server_sock = socket(PF_INET, SOCK_STREAM, 0);
	
	memset(&server_address,0,sizeof(server_address));
    server_address.sin_family = AF_INET;
    server_address.sin_addr.s_addr =htonl(INADDR_ANY);
    server_address.sin_port = htons(PORT);
	
    if(bind(server_sock, (struct sockaddr *)&server_address, sizeof(server_address)) == -1)
	{
		printf("bind error");
		exit(1);
	}

    if(listen(server_sock, QUEUE) == -1)
	{
		printf("listen error");
		exit(1);
	}
    
    /* 接受连接 */
    int client_sock;
	struct sockaddr_in client_address;
	int client_len = sizeof(client_address);
	
    client_sock = accept(server_sock, (struct sockaddr *)&client_address, &client_len);
	if(client_sock < 0)
	{
		printf("accept error");
        exit(1);
	}
	
	char buffer[BUFFER_SIZE];
    while(1) {
        memset(buffer, 0, sizeof(buffer));
		int len = recv(client_sock, buffer, sizeof(buffer),0);//缓冲区长度
        if(strcmp(buffer,"exit\n")==0)
            break;
		fputs(buffer, stdout);
        send(client_sock, buffer, len, 0);//数据长度
    }
	close(client_sock);
	exit(0);
}

